package com.javatip.project.deep_learning.model.service;

import java.io.File;
import java.util.Date;
import java.util.List;

import com.javatip.common.utils.file.FileUtils;
import com.javatip.framework.web.domain.AjaxResult;
import com.javatip.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javatip.project.deep_learning.model.mapper.ModelMapper;
import com.javatip.project.deep_learning.model.domain.Model;
import com.javatip.common.utils.text.Convert;

import static com.javatip.common.utils.security.ShiroUtils.getSysUser;


/**
 * 模型 服务层实现
 * 
 * @author 袁伟
 * @date 2024-06-18
 */
@Service
public class ModelServiceImpl implements IModelService 
{
	@Autowired
	private ModelMapper modelMapper;

	/**
     * 查询模型信息
     * 
     * @param id 模型ID
     * @return 模型信息
     */
    @Override
	public Model selectModelById(Integer id)
	{
	    return modelMapper.selectModelById(id);
	}
	
	/**
     * 查询模型列表
     * 
     * @param model 模型信息
     * @return 模型集合
     */
	@Override
	public List<Model> selectModelList(Model model)
	{
	    return modelMapper.selectModelList(model);
	}
	
    /**
     * 新增模型
     * 
     * @param model 模型信息
     * @return 结果
     */
	@Override
	public int insertModel(Model model)
	{
//		model的创建时间设置为当前时间
		model.setUploadTime(new Date());
		User currentUser = getSysUser();
		model.setUserId(Integer.parseInt(String.valueOf(currentUser.getUserId())));
	    return modelMapper.insertModel(model);
	}
	
	/**
     * 修改模型
     * 
     * @param model 模型信息
     * @return 结果
     */
	@Override
	public int updateModel(Model model)
	{
	    return modelMapper.updateModel(model);
	}

	/**
     * 删除模型对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteModelByIds(String ids)
	{
		return modelMapper.deleteModelByIds(Convert.toStrArray(ids));
	}



	@Override
	public AjaxResult deleteModelByIdsandLocation(String ids, String location) {
		try {
			// 获取location的上一级目录
			File parentFolder = new File(location).getParentFile();
			int result= modelMapper.deleteModelByIds(Convert.toStrArray(ids));
			if (result > 0) {
				FileUtils.deleteFolderFile(parentFolder.toString()); // 删除文件夹及其内容
				return AjaxResult.success("删除成功");
			}else {
				return AjaxResult.error("删除失败");
			}
		} catch (Exception e) {
			// 异常处理逻辑
			return AjaxResult.deleteError();
		}
	}

	@Override
	public boolean isTrainModelNameExists(String name, int userId) {
		Integer count = modelMapper.isModelNameExists(name,userId);
		return count != null && count > 0;
	}

}
